package sso.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import sso.mapper.UserMapper;

import java.util.List;
import java.util.Map;

/**
 * 通过此对象处理登录请求
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.基于用户名查询用户信息
        Map<String, Object> map = userMapper.selectUserByUsername(username);
        if (map==null) throw new UsernameNotFoundException("username not exits");
        //Userinfo info=userDao.selectUserByUsername(username);
        //if(info==null)throw new UsernameNotFoundException();
        //2.查询用户权限信息并封装查询结果
        List<String> list = userMapper.seelctUserPermissions((Long) map.get("id"));
        /*String password=passwordEncoder.encode("123456");
        System.out.println("password="+password);
        List<GrantedAuthority> grantedAuthorities =
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                        "sys:res:retrieve,sys:res:create");*/
        //权限信息后续要从数据库去查
        return new User(username,(String) map.get("password"),AuthorityUtils.createAuthorityList
                  (list. toArray(new String[]{})));
        //这个值返回给谁?谁调用此方法这个就返回给谁.
    }
}
